<template>
  <div class="patient-inspection-page">
    <!-- 左侧患者列表区域 -->
    <div class="left-panel">
      <el-input
        v-model="searchName"
        placeholder="患者名"
        clearable
        style="margin-bottom: 10px"
        @keyup.enter="fetchUninspectedPatients"
      >
        <template #append>
          <el-button icon="el-icon-search" @click="fetchUninspectedPatients"></el-button>
        </template>
      </el-input>
      <el-tree
        :data="patientTreeData"
        :props="treeProps"
        node-key="caseNumber"
        default-expand-all
        @node-click="handlePatientClick"
        style="height: calc(100% - 50px); overflow-y: auto"
      >
        <template #default="{ node }">
         
        </template>
      </el-tree>
    </div>
    <!-- 右侧检验信息区域 -->
    <div class="right-panel">
      <!-- 操作按钮 -->
      <div class="operation-btns">
        <el-button type="primary" @click="handleConfirm">执行确认</el-button>
        <el-button @click="handleCancel">取消执行</el-button>
        <el-button @click="handleFillResult">填写结果</el-button>
      </div>
      <!-- 检验明细单 -->
      <div class="inspection-info">
        <h3>检验明细单</h3>
        <el-form label-width="100px" size="medium">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="病历号">
                <el-input v-model="patientInfo.caseNumber" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="患者姓名">
                <el-input v-model="patientInfo.patientName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="年龄">
                <el-input v-model="patientInfo.age" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="结算类别">
                <!-- 这里结算类别可根据 settlementTypeId 去关联字典表展示，简单示例直接显示 ID -->
                <el-input v-model="patientInfo.settlementTypeId" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="就诊科室">
                <!-- 科室可根据 departmentId 关联科室表，示例显示 ID -->
                <el-input v-model="patientInfo.departmentId" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="处方状态">
                <el-input v-model="patientInfo.visitStatusDesc" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="收费日期">
                <el-input v-model="patientInfo.registrationTime" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开单医生">
                <!-- 医生可根据 doctorId 关联医生表，示例显示 ID -->
                <el-input v-model="patientInfo.doctorId" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发票号">
                <el-input v-model="patientInfo.invoiceNo" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 检验信息表格 -->
      <div class="inspection-table">
        <h3>检验信息</h3>
        <el-table :data="inspectionTableData" border style="width: 100%">
          <el-table-column prop="itemName" label="检验名称" />
          <el-table-column prop="inspectionPart" label="检验部位" />
          <el-table-column prop="num" label="数量" />
          <el-table-column prop="unit" label="单位" />
          <el-table-column prop="price" label="单价" />
          <el-table-column prop="totalPrice" label="总金额" />
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              {{ scope.row.status === 2 ? '收费未检验' : '已检验' }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <!-- 填写检验结果对话框 -->
    <!-- 填写检验结果对话框 -->
    <el-dialog
  title="填写检验结果"
  v-model="resultDialogVisible"
  width="60%"
  @close="resetResultForm"
>
  <!-- 改用默认插槽 #default（或直接写内容） -->
  <template #default>
    <el-form :model="resultForm" label-width="120px">
      <el-form-item label="检验结论" required>
        <el-input 
          type="textarea" 
          :rows="4" 
          v-model="resultForm.conclusion"
          placeholder="请输入检验结论"
        ></el-input>
      </el-form-item>
      <!-- 其他表单项... -->
    </el-form>
  </template>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="resultDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveInspectionResult">保存结果</el-button>
    </span>
  </template>
</el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElTree, ElInput, ElButton, ElForm, ElFormItem, ElRow, ElCol, ElTable, ElTableColumn, ElUpload, ElDialog, ElDatePicker } from 'element-plus'
import service from '@/utils/request.js' // 假设已封装 axios 实例，根据实际路径调整
// 确认变量已正确定义

// 响应式数据
const searchName = ref('') // 患者搜索名称
const patientTreeData = ref([]) // 左侧患者树数据（模拟医技检验分类）
const treeProps = {
  children: 'children',
  label: 'label'
}
const patientInfo = reactive({
  caseNumber: '',
  patientName: '',
  age: '',
  settlementTypeId: '',
  departmentId: '',
  visitStatus: '',
  registrationTime: '',
  doctorId: '',
  invoiceNo: '',
  visitStatusDesc: computed(() => {
    // 根据 visitStatus 映射状态描述，可扩展更多状态
    return patientInfo.visitStatus === 2 ? '收费未检验' : '其他状态' 
  })
})
const inspectionTableData = ref([]) // 检验信息表格数据
const currentRegistrationId = ref('') // 记录当前患者 registrationId（对应后端 id）
const resultDialogVisible = ref(false) // 填写结果对话框显隐
const uploadUrl = ref('/upload/inspectionResult') // 上传URL，可在组件加载时设置或动态生成

// 检验结果表单数据
const resultForm = reactive({
  conclusion: '',     // 检验结论
  diagnosis: '',      // 诊断意见
  doctor: '',         // 检验医生
  date: new Date(),   // 检验日期，默认今天
  fileList: []        // 上传文件列表
})

// 初始化：获取收费未检验患者列表
onMounted(() => {
  fetchUninspectedPatients()
})

// 获取收费未检验患者（调用后端 getByStatus 接口，visitStatus=2）
async function fetchUninspectedPatients() {
  try {
    const res = await service.get('/registration/getByStatus', {
      params: { 
        visitStatus: 2
      }
    })
    // 因为 request 已解析 data，直接用 res 作为数据数组
    const patientList = res || []; 
    // 构建左侧患者树结构，映射后端 Registration 实体类字段
    patientTreeData.value = [
      {
        label: '医技检验',
        children: patientList.map(item => ({
          label: item.patientName || '未知姓名',
          caseNumber: item.caseNumber || '',
          age: item.age || '',
          registrationId: item.id, // 后端实体类主键是 id，对应前端 registrationId 用于后续请求
          // 可按需映射更多字段到节点，方便后续使用
          patientName: item.patientName,
          settlementTypeId: item.settlementTypeId,
          departmentId: item.departmentId,
          visitStatus: item.visitStatus,
          registrationTime: item.registrationTime,
          doctorId: item.doctorId,
          invoiceNo: item.invoiceNo
        }))
      }
    ]
  } catch (err) {
    ElMessage.error('获取患者列表失败：' + err.message)
  }
}

// 点击患者节点：加载检验明细与检验信息
// 点击患者节点：加载检验明细与检验信息
async function handlePatientClick(node) {
  if (node.registrationId) { // 确保是患者节点
    currentRegistrationId.value = node.registrationId
    // 1. 获取患者基本信息（检验明细单），这里可直接从节点映射的字段赋值，也可再次调用 /registration/checkCaseNumber 接口
    // 示例：直接从节点映射字段赋值
    patientInfo.caseNumber = node.caseNumber
    patientInfo.patientName = node.patientName
    patientInfo.age = node.age
    patientInfo.settlementTypeId = node.settlementTypeId
    patientInfo.departmentId = node.departmentId
    patientInfo.visitStatus = node.visitStatus
    patientInfo.registrationTime = node.registrationTime
    patientInfo.doctorId = node.doctorId
    patientInfo.invoiceNo = node.invoiceNo

    // 2. 获取检验项目信息，调用 /examApp/list 接口，参数用 registrationId（即后端的 id）
    const examRes = await service.get('/examApp/list', {
      params: { registrationId: node.registrationId }
    })
    // 处理检验信息表格数据，映射后端返回字段（假设 request 已解析 data，直接用 examRes）
    const examList = examRes || [];
    inspectionTableData.value = examList.map(item => ({
      itemName: item.itemName,
      inspectionPart: item.inspectionPart || '',
      num: item.quantity,
      unit: item.unit || '',
      price: item.price,
      totalPrice: item.price * item.quantity,
      status: item.status // 后端返回的状态，用于判断显示“收费未检验”等
    }))
  }
}

async function handleConfirm() {
  if (!currentRegistrationId.value) { // 正确的变量名
    ElMessage.warning('请选择患者');
    return;
  }
  try {
    await ElMessageBox.confirm(
      '确认执行检验？执行后状态将改为“检验未确诊”',
      '确认提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    // 修正：将 registrationId 改为 currentRegistrationId
    const res = await service.post(
      "examApp/updateStatus", 
      null,
      {
        params: {  
          registrationId: currentRegistrationId.value, // 正确变量名
          status: 3
        }
      }
    );
    await service.post(
      "registration/status", 
      null,
      {
        params: {  
          registrationId: currentRegistrationId.value, // 正确变量名
          status: 3
        }
      }
    );
   
    ElMessage.success('执行确认成功，状态已更新');
    fetchUninspectedPatients(); // 刷新患者列表
    resetPatientInfo(); // 重置当前患者信息
    
  } catch (err) {
    // 错误处理：err 可能是后端返回的 msg，或网络错误
    if (err === 'cancel') return; // 忽略用户取消操作
    ElMessage.error('执行确认失败：' + (err.message || err || '未知错误'));
  }
}

// 取消执行（可根据需求实现，比如改回收费未检验状态，即 visitStatus=2 ，需与后端约定接口）
function handleCancel() {
  ElMessage.info('取消执行逻辑需补充，可调用接口将 visitStatus 改回 2 等')
}

// 填写结果（弹出对话框）
function handleFillResult() {
  console.log('点击了填写结果按钮'); // 新增日志，验证方法是否被调用
  if (!currentRegistrationId.value) {
    ElMessage.warning('请选择患者');
    return;
  }
  resultDialogVisible.value = true; // 核心：显示对话框
  console.log('准备显示对话框，resultDialogVisible:', resultDialogVisible.value); // 验证变量是否被正确设置
}

// 保存检验结果（适配新接口）
async function saveInspectionResult() {
  // 表单验证
  if (!resultForm.conclusion) {
    ElMessage.warning('请输入检验结论');
    return;
  }
  
  try {
    // 1. 处理文件上传（如有）
    let fileUrls = [];
    if (resultForm.fileList.length > 0) {
      const uploadPromises = resultForm.fileList.map(file => {
        if (!file.url) { // 仅上传未上传的文件
          const formData = new FormData();
          formData.append('file', file.raw);
          formData.append('registrationId', currentRegistrationId.value);
          return service.post(uploadUrl.value, formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
          });
        }
        return Promise.resolve({ data: { fileUrl: file.url } });
      });
      
      const uploadResults = await Promise.all(uploadPromises);
      fileUrls = uploadResults.map(res => res.data?.fileUrl || '');
    }
    
    // 2. 构建检验结果字符串（结构化存储到 examination_result 字段）
    const examinationResult = `
      检验结论：${resultForm.conclusion}
      诊断意见：${resultForm.diagnosis || '无'}
      检验医生：${resultForm.doctor || '未知'}
      检验日期：${resultForm.date || new Date().toLocaleDateString()}
      附件地址：${fileUrls.join('; ')}
    `.trim(); // 去除首尾空行，避免多余空格
    
    // 3. 调用后端接口更新病历表
    const res = await service.post(
      '/medicalRecord/updateExaminationResult',
      null,
      {
        params: {
          registrationId: currentRegistrationId.value, // 关联的挂号ID
          examinationResult: examinationResult // 检验结果内容
        }
      }
    );
    
    // 4. 处理成功响应
    ElMessage.success('检验结果保存成功');
    resultDialogVisible.value = false; // 关闭对话框
    resetResultForm(); // 重置表单
    
  } catch (err) {
    // 5. 处理错误（包括接口失败、用户取消等）
    if (err === 'cancel') return;
    ElMessage.error('保存异常：' + (err.message || err || '未知错误'));
  }
}

// 自定义文件上传
function customUpload(options) {
  const formData = new FormData()
  formData.append('file', options.file)
  formData.append('registrationId', currentRegistrationId.value)
  
  service.post(uploadUrl.value, formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  }).then(res => {
    if (res.code === 200) {
      ElMessage.success('文件上传成功')
      resultForm.fileList.push({ ...options.file, url: res.data.fileUrl })
    } else {
      ElMessage.error('文件上传失败：' + res.msg)
    }
  }).catch(err => {
    ElMessage.error('文件上传异常：' + err.message)
  })
}

// 文件上传前校验
function beforeFileUpload(file) {
  const isDoc = file.type === 'application/msword' || 
                file.type === 'application/pdf' || 
                file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  
  if (!isDoc) {
    ElMessage.error('仅支持上传 Word 或 PDF 文件')
  }
  return isDoc
}

// 文件移除回调
function handleFileRemove(file, fileList) {
  // 从表单文件列表中移除
  resultForm.fileList = fileList
  // 可扩展：调用后端接口删除已上传文件
  if (file.url) {
    // 示例：异步删除服务器文件
    service.post('/deleteFile', { fileUrl: file.url })
      .catch(err => ElMessage.error('删除服务器文件失败：' + err.message))
  }
}

// 重置患者信息
function resetPatientInfo() {
  patientInfo.caseNumber = ''
  patientInfo.realname = ''
  patientInfo.age = ''
  patientInfo.settlementType = ''
  patientInfo.department = ''
  patientInfo.prescriptionStatus = ''
  patientInfo.chargeDate = ''
  patientInfo.doctor = ''
  patientInfo.invoiceNo = ''
  inspectionTableData.value = []
  currentRegistrationId.value = ''
}

// 重置结果表单
function resetResultForm() {
  resultForm.conclusion = ''
  resultForm.diagnosis = ''
  resultForm.doctor = ''
  resultForm.date = new Date()
  resultForm.fileList = []
}
</script>

<style scoped>
.patient-inspection-page {
  display: flex;
  height: calc(100vh - 60px);
}
.left-panel {
  width: 300px;
  border-right: 1px solid #e6e6e6;
  padding: 20px;
}
.right-panel {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
}
.operation-btns {
  margin-bottom: 20px;
}
.inspection-info, .inspection-table {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
}
.inspection-info h3, .inspection-table h3 {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}
.el-tree {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 10px;
}
</style>